
import pygame
from MazeData import MazeData,MazeData2



class MazeGame(object):
    def __init__(self, row, col):
        self.row = row
        self.col = col
        self.size = 9
        self.screenWidth = self.col * self.size
        self.screenHeight = self.row * self.size
        self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight))
        pygame.display.set_caption("迷宫游戏")
        self.mazeData = MazeData2(row, col)
        print(type(self.mazeData))
        print(dir(self.mazeData))
        self.update_GUI()

    def play(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_g:
                        if self.go(0, 0):
                            print("Succeed!")
                        else:
                            print("此迷宫无解！")
                    if event.key == pygame.K_q:
                        exit()

    def go(self, row, col):
        DrawTools.DrawRect(self.screen, row, col, self.size, (255, 0, 0))# 红色
        for dCol, dRow in self.mazeData.direction:
            if self.mazeData.isInArea(row + dRow, col + dCol) and (
                    not self.mazeData.visited[row + dRow][col + dCol] and (
                    self.mazeData.data[row + dRow][col + dCol] == ' ')):
                self.mazeData.visited[row + dRow][col + dCol] = True
                if [row + dRow, col + dCol] == self.mazeData.exit:
                    DrawTools.DrawRect(self.screen, row + dRow, col + dCol, self.size, (255, 0, 0))
                    return True
                if self.go(row + dRow, col + dCol):
                    return True
        DrawTools.DrawRect(self.screen, row, col, self.size, (255, 255, 255))

    def update_GUI(self):
        self.screen.fill((255, 255, 255))
        for i, row in enumerate(self.mazeData.data):
            for j, col in enumerate(row):
                if col == '#':
                    cell = pygame.Rect(j * self.size, i * self.size, self.size, self.size)
                    pygame.draw.rect(self.screen, (10, 10, 200), cell)
        pygame.display.update()


class DrawTools(object):
    @staticmethod
    def DrawRect(screen, row, col, size, color):
        cell = pygame.Rect(col * size, row * size, size, size)
        pygame.draw.rect(screen, color, cell)
        pygame.display.update()


if __name__ == "__main__":
    maze = MazeGame(39, 23)
    maze.play()
